package com.lonely.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.goods.domain.entity.SysGoodsProcessItem;
import com.lonely.goods.service.IGoodsProcessItemService;
import com.lonely.order.domain.entity.SysOrderProcess;
import com.lonely.order.domain.entity.SysOrderProcessItem;
import com.lonely.order.mapper.SysOrderProcessItemMapper;
import com.lonely.order.service.IOrderProcessItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单工序明细服务实现类
 *
 * @author fzzf
 */
@Service
public class OrderProcessItemServiceImpl extends ServiceImpl<SysOrderProcessItemMapper, SysOrderProcessItem> implements IOrderProcessItemService {

    @Autowired
    private IGoodsProcessItemService goodsProcessItemService;

    /**
     * 创建订单工序明细
     *
     * @param sysOrderProcess
     * @param goodsProcessId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createOrderProcessItems(SysOrderProcess sysOrderProcess, Long goodsProcessId) {
        List<SysGoodsProcessItem> goodsProcessItems = this.goodsProcessItemService.list(new LambdaQueryWrapper<SysGoodsProcessItem>()
                .eq(SysGoodsProcessItem::getGoodsProcessId, goodsProcessId)
        );
        if (CollUtil.isEmpty(goodsProcessItems)) {
            return;
        }

        List<SysOrderProcessItem> orderProcessItems = goodsProcessItems.stream().map(goodsProcessItem -> {
            SysOrderProcessItem sysOrderProcessItem = new SysOrderProcessItem();
            BeanUtils.copyProperties(goodsProcessItem, sysOrderProcessItem);
            sysOrderProcessItem.setOrderProcessId(sysOrderProcess.getId());
            sysOrderProcessItem.setCreateBy(SecurityUtils.getUserId());
            sysOrderProcessItem.setUpdateBy(SecurityUtils.getUserId());
            return sysOrderProcessItem;
        }).collect(Collectors.toList());
        super.saveBatch(orderProcessItems);
    }
}
